package org.fuxia.im.common;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.swing.ImageIcon;

/**
 * 图片管理器
 *
 */
public class IconManager {
	
	private static final Set<String> iconSuffix ;
	private static final String ICON_PATH = "images" ;
	private static final  Map<String,ImageIcon> icons;
	private static final Map<String,String> 	iconsPath ;
	private static IconManager instance;
	
	
	static{
		iconsPath = new HashMap<String, String>();
		icons = new HashMap<String,ImageIcon>();
		iconSuffix = new HashSet<String>() ;
		iconSuffix.add("jpg");
		iconSuffix.add("png");
		iconSuffix.add("ico");
		iconSuffix.add("gif");
	}
	
	private IconManager(){
		try {
			URL url = Thread.currentThread().getContextClassLoader().getResource(ICON_PATH) ;
			if(url!=null) {
				File iconDir = new File(url.toURI());
				File[] files = iconDir.listFiles() ;
				for(File sub :files) {
					String key = getKey(iconDir.getName()+"/"+sub.getName());
					if(key !=null) {
						iconsPath.put(key, sub.getAbsolutePath()) ;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace() ;
			//
		}
	}
	
	public static IconManager lazyInit() {
		instance =new IconManager() ;
		return instance ;
	}
	
	private static String getKey(String fileName) {
		int index = fileName.lastIndexOf(".") ;
		if(index == -1) {
			return null ;
		}else {
			String suffix = fileName.substring(index+1) ;
			if(iconSuffix.contains(suffix)) {
				return fileName ;
			}
			return null ;
		}
		
	}
	
	public static synchronized ImageIcon getIcon(String iconName) {
		ImageIcon icon = icons.get(iconName) ;
		if(icon == null) {
			if(iconsPath.containsKey(iconName)) {
				icon = new ImageIcon(iconsPath.get(iconName));
				icons.put(iconName, icon);
				return icon ;
			}
		}
		return icon;
	}
	
	public static int getSize(){
		return icons.size();
	}
	
	public static void main(String[] args) {
		IconManager.lazyInit();
	}

}
